# ==================================================
#  0. 国内网络加速说明（已内置）
#  - Alpine 使用清华源（ARM 友好，路径正确）
#  - NPM / PNPM 使用 npmmirror
#  - Go 使用 goproxy.cn
#  构建命令（ARM 示例）：
#  DOCKER_BUILDKIT=1  docker  build  \
#    --platform  linux/arm/v7  \
#    --build-arg  COMMIT=$(git rev-parse --short HEAD) \
#    --build-arg  VERSION=$(git describe --tags --always) \
#    --build-arg  BUILD_TIME=$(date -u +"%Y-%m-%dT%H:%M:%SZ") \
#    -t  homebox-enhanced  .
# ==================================================

# --------------------------------------------------
# ① 前端依赖 + 构建（合并阶段）
# --------------------------------------------------
FROM public.ecr.aws/docker/library/node:lts-alpine AS frontend-builder
WORKDIR /app

# 0) Alpine 换源（清华源，路径正确）
RUN sed -i 's|https://dl-cdn.alpinelinux.org|https://mirrors.tuna.tsinghua.edu.cn|g' /etc/apk/repositories

# 1) NPM / PNPM 换源 + 全局安装 pnpm
RUN npm config set registry https://registry.npmmirror.com && \
    npm install -g pnpm && \
    pnpm config set registry https://registry.npmmirror.com

# 2) 依赖缓存层（BuildKit 缓存）
COPY frontend/package.json frontend/pnpm-lock.yaml ./
RUN --mount=type=cache,id=pnpm-store,target=/root/.local/share/pnpm/store \
    pnpm fetch --frozen-lockfile

# 3) 源码 + 离线安装 + 构建
COPY frontend .
RUN --mount=type=cache,id=pnpm-store,target=/root/.local/share/pnpm/store \
    pnpm install --offline --frozen-lockfile && \
    pnpm build

# --------------------------------------------------
# ② Go 模块缓存阶段
# --------------------------------------------------
FROM public.ecr.aws/docker/library/golang:alpine AS builder-dependencies
WORKDIR /go/src/app

# 0) Alpine 换源
RUN sed -i 's|https://dl-cdn.alpinelinux.org|https://mirrors.tuna.tsinghua.edu.cn|g' /etc/apk/repositories

# 1) Go 国内代理
ENV GOPROXY=https://goproxy.cn,direct
ENV GOSUMDB=off

COPY backend/go.mod backend/go.sum ./
RUN --mount=type=cache,id=go-mod,target=/go/pkg/mod \
    go mod download

# --------------------------------------------------
# ③ Go 编译阶段
# --------------------------------------------------
FROM public.ecr.aws/docker/library/golang:alpine AS builder
ARG TARGETOS
ARG TARGETARCH
ARG BUILD_TIME
ARG COMMIT
ARG VERSION

# 0) Alpine 换源 + 编译工具
RUN sed -i 's|https://dl-cdn.alpinelinux.org|https://mirrors.tuna.tsinghua.edu.cn|g' /etc/apk/repositories
RUN apk add --no-cache git build-base
# 仅 x86_64 / amd64 等正常架构才装图像库
RUN if [ "$TARGETARCH" != "arm" ] && [ "$TARGETARCH" != "riscv64" ]; then \
        apk add --no-cache libwebp libavif libheif libjxl; \
    fi

WORKDIR /go/src/app

# 1) 复用 mod 缓存
#COPY --from=builder-dependencies /go/pkg/mod /go/pkg/mod
ENV GOPROXY=https://goproxy.cn,direct
ENV GOSUMDB=off

COPY backend .

# 2) 嵌入前端产物
RUN rm -rf ./app/api/public
COPY --from=frontend-builder /app/.output/public ./app/api/static/public

# 3) 编译（缓存 go-build）
RUN --mount=type=cache,id=go-build,target=/root/.cache/go-build \
    CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build \
      -ldflags "-s -w -X main.commit=${COMMIT} -X main.buildTime=${BUILD_TIME} -X main.version=${VERSION}" \
      -tags "netgo,osusergo,$(if [ "$TARGETARCH" = "arm" ] || [ "$TARGETARCH" = "riscv64" ]; then echo nodynamic; fi)" \
      -o /go/bin/api ./app/api

# --------------------------------------------------
# ④ 生产镜像
# --------------------------------------------------
FROM public.ecr.aws/docker/library/alpine:latest
ARG TARGETARCH

# 0) Alpine 换源 + 运行时依赖
RUN sed -i 's|https://dl-cdn.alpinelinux.org|https://mirrors.tuna.tsinghua.edu.cn|g' /etc/apk/repositories
RUN apk add --no-cache ca-certificates wget && \
    if [ "$TARGETARCH" != "arm" ] && [ "$TARGETARCH" != "riscv64" ]; then \
        apk add --no-cache libwebp libavif libheif libjxl; \
    fi

ENV HBOX_MODE=production
ENV HBOX_STORAGE_CONN_STRING=file:///?no_tmp_dir=true
ENV HBOX_STORAGE_PREFIX_PATH=data
ENV HBOX_DATABASE_SQLITE_PATH=/data/homebox.db?_pragma=busy_timeout=2000&_pragma=journal_mode=WAL&_fk=1&_time_format=sqlite

RUN mkdir /app
COPY --from=builder /go/bin/api /app/api
RUN chmod +x /app/api

LABEL Name=homebox Version=0.0.1
LABEL org.opencontainers.image.source="https://github.com/sysadminsmedia/homebox"

EXPOSE 7745
WORKDIR /app

HEALTHCHECK --interval=30s --timeout=5s --start-period=5s --retries=3 \
  CMD wget --no-verbose -O - http://localhost:7745/api/v1/status || exit 1

VOLUME ["/data"]
ENTRYPOINT ["/app/api"]
CMD ["/data/config.yml"]